// 定义一个存储和读取localStorage的工具

class Storage{
  constructor () {
    this.STORAGE_NAME = 'snack_shop' // 缓存的名称
    this.STORAGE_TYPE = 'localStorage' // 缓存的方式localstorage还是sessionStorage或者cookie
  }

  getAllData () {// 先获取下该缓存的东西有没有
    let storageData = window[this.STORAGE_TYPE].getItem(this.STORAGE_NAME)
    storageData = storageData?JSON.parse(storageData):{} // 如果有就序列化，没有就赋值为一个空对象
    return storageData
  }

  saveStorage (key, data)  {
    
    let storageData = this.getAllData()
    // 存进的参数
    storageData[key] = data

    // 存
    window[this.STORAGE_TYPE].setItem(this.STORAGE_NAME,JSON.stringify(storageData))
  }
  
  getStorage (key) {
    let storageData = this.getAllData()
    // 检查存储中有没有这个键名
    if(storageData.hasOwnProperty(key)){
      return storageData[key]
    }
    return null
  }

  removeStorage (key) {
    let storageData = this.getAllData()
  
    if(storageData.hasOwnProperty(key)){
      storageData[key] = null
      console.log('有这个key');
      window[this.STORAGE_TYPE].setItem(this.STORAGE_NAME,JSON.stringify(storageData))
    }
  }
}

export default Storage
